"""
更新 cjdev 工具本身
"""
import subprocess
from pathlib import Path

import click
from config import Config
from i18n import (
    t,
    set_language as set_runtime_language,
    get_supported_languages,
)

LANGUAGE_CHOICES = [lang for lang in get_supported_languages()]


def _ensure_language(cfg: Config):
    if cfg.has_language_config():
        set_runtime_language(cfg.get_language())
        return
    click.echo(t("update.language.notice"))
    choice = click.prompt(
        t("update.language.prompt"),
        default=cfg.get_language(),
        type=click.Choice(LANGUAGE_CHOICES, case_sensitive=False),
    )
    lang = choice.lower()
    cfg.set_language(lang)
    set_runtime_language(lang)
    click.echo(t("update.language.saved", language=t(f"language.label.{lang}")))


@click.command()
def update():
    """
    在 cjdev 项目目录执行 git pull，以获取最新功能。
    """
    cfg = Config()
    _ensure_language(cfg)

    repo_root = Path(__file__).resolve().parents[1]
    click.echo(t("update.start", path=repo_root))

    result = subprocess.run(
        ["git", "pull"],
        cwd=repo_root,
        capture_output=True,
        text=True
    )

    if result.returncode == 0:
        if result.stdout.strip():
            click.echo(result.stdout.strip())
        click.echo(t("update.success"))
    else:
        click.echo(t("update.failed_heading"), err=True)
        click.echo(result.stderr.strip() or result.stdout.strip(), err=True)
        raise SystemExit(result.returncode)

